/*
//*The wixServer based ESP8266 Soc.
//*Author: openthings@163.com.
//*copyright & GPL V2.
//*Last modified 2014-10-23.
//*/
//
//#include "c_types.h"
//#include "user_interface.h"
//#include "xc_version.h"
//#include "espconn.h"
//#include "mem.h"
//#include "xc.h"
////#include "xc_ipCmd.h"
//#include "osapi.h"
//#include "driver/uart.h"
//
//extern at_mdStateType mdState;
//extern BOOL specialAtState;
//extern at_stateType at_state;
//extern at_funcationType at_fun[];
//extern uint8_t *pDataLine;
//extern uint8_t at_dataLine[];///
////extern uint8_t *at_dataLine;
////extern UartDevice UartDev;
//extern uint8_t at_wifiMode;
//extern int8_t at_dataStrCpy(void *pDest, const void *pSrc, int8_t maxLen);
//
////extern ip_addr_t host_ip;
//ip_addr_t host_ip;
//
///////////////////////////////////
//#define ESP_PARAM_SAVE_SEC_0    1
//#define ESP_PARAM_SAVE_SEC_1    2
//#define ESP_PARAM_SEC_FLAG      3
//
//#define UPGRADE_FRAME  "{\"path\": \"/v1/messages/\", \"method\": \"POST\", \"meta\": {\"Authorization\": \"token %s\"},\
//\"get\":{\"action\":\"%s\"},\"body\":{\"pre_rom_version\":\"%s\",\"rom_version\":\"%s\"}}\n"
//
//#define pheadbuffer "Connection: keep-alive\r\n\
//Cache-Control: no-cache\r\n\
//User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 \r\n\
//Accept: */*\r\n\
//Authorization: token %s\r\n\
//Accept-Encoding: gzip,deflate,sdch\r\n\
//Accept-Language: zh-CN,zh;q=0.8\r\n\r\n"
//
//#define pheadbuffer "Connection: keep-alive\r\n\
//Cache-Control: no-cache\r\n\
//User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 \r\n\
//Accept: */*\r\n\
//Authorization: token %s\r\n\
//Accept-Encoding: gzip,deflate,sdch\r\n\
//Accept-Language: zh-CN,zh;q=0.8\r\n\r\n"
//
//#define test 1
//#ifdef test
//#define KEY "39cdfe29a1863489e788efc339f514d78b78f0de"
//#else
//#define KEY "4ec90c1abbd5ffc0b339f34560a2eb8d71733861"
//#endif
//
//struct espconn *pespconn;
//struct upgrade_server_info *upServer = NULL;
//struct esp_platform_saved_param {
//    uint8 devkey[40];
//    uint8 token[40];
//    uint8 activeflag;
//    uint8 pad[3];
//};
//struct esp_platform_sec_flag_param {
//    uint8 flag;
//    uint8 pad[3];
//};
////static struct esp_platform_saved_param esp_param;
//
///******************************************************************************
// * FunctionName : user_esp_platform_upgrade_cb
// * Description  : Processing the downloaded data from the server
// * Parameters   : pespconn -- the espconn used to connetion with the host
// * Returns      : none
//*******************************************************************************/
//LOCAL void ICACHE_FLASH_ATTR
//at_upDate_rsp(void *arg)
//{
//	struct upgrade_server_info *server = arg;
//	//  struct espconn *pespconn = server->pespconn;
//	//  uint8 *pbuf = NULL;
//	//  char *action = NULL;
//	//  char temp[32];
//
//	//  if(pespconn->proto.tcp != NULL)
//	//  {
//	//    os_free(pespconn->proto.tcp);
//	//  }
//	//  os_free(pespconn);
//
//	if(server->upgrade_flag == true)
//	{
//		//    pbuf = (char *) os_zalloc(2048);
//		//        ESP_DBG("user_esp_platform_upgarde_successfully\n");
//		os_printf("device_upgrade_success\r\n");
//		//    action = "device_upgrade_success";
//		at_backOk;
//		system_upgrade_reboot();
//		//    os_sprintf(pbuf, UPGRADE_FRAME,
//		//               devkey, action,
//		//               server->pre_version,
//		//               server->upgrade_version);
//		//        ESP_DBG(pbuf);
//
//		//    espconn_sent(pespconn, pbuf, os_strlen(pbuf));
//
//		//    if(pbuf != NULL)
//		//    {
//		//      os_free(pbuf);
//		//      pbuf = NULL;
//		//    }
//	}
//	else
//	{
//		//        ESP_DBG("user_esp_platform_upgrade_failed\n");
//		os_printf("device_upgrade_failed\r\n");
//		//    action = "device_upgrade_failed";
//		//    os_sprintf(pbuf, UPGRADE_FRAME, devkey, action);
//		//        ESP_DBG(pbuf);
//		//    os_sprintf(temp, at_backTeError, 1);
//		//    uart0_sendStr(at_backTeError"1\r\n");
//		at_backError;
//		//    espconn_sent(pespconn, pbuf, os_strlen(pbuf));
//
//		//    if(pbuf != NULL)
//		//    {
//		//      os_free(pbuf);
//		//      pbuf = NULL;
//		//    }
//	}
//
//	os_free(server->url);
//	server->url = NULL;
//	os_free(server);
//	server = NULL;
//
//	//  espconn_disconnect(pespconn);
//	specialAtState = TRUE;
//	at_state = at_statIdle;
//}
//
/////******************************************************************************
//// * FunctionName : user_esp_platform_load_param
//// * Description  : load parameter from flash, toggle use two sector by flag value.
//// * Parameters   : param--the parame point which write the flash
//// * Returns      : none
////*******************************************************************************/
////void ICACHE_FLASH_ATTR
////user_esp_platform_load_param(struct esp_platform_saved_param *param)
////{
////    struct esp_platform_sec_flag_param flag;
////
////    load_user_param(ESP_PARAM_SEC_FLAG, 0, &flag, sizeof(struct esp_platform_sec_flag_param));
////
////    if (flag.flag == 0) {
////        load_user_param(ESP_PARAM_SAVE_SEC_0, 0, param, sizeof(struct esp_platform_saved_param));
////    } else {
////        load_user_param(ESP_PARAM_SAVE_SEC_1, 0, param, sizeof(struct esp_platform_saved_param));
////    }
////}
//
///**
//  * @brief  Tcp client disconnect success callback function.
//  * @param  arg: contain the ip link information
//  * @retval None
//  */
//static void ICACHE_FLASH_ATTR
//at_upDate_discon_cb(void *arg)
//{
//	struct espconn *pespconn = (struct espconn *)arg;
//	uint8_t idTemp;
//
//	if(pespconn == NULL)
//	{
//		return;
//	}
//	if(pespconn->proto.tcp != NULL)
//	{
//		os_free(pespconn->proto.tcp);
//	}
//	os_free(pespconn);
//
//	os_printf("disconnect\r\n");
//
//	//comment by wangeq.
//	/*
//	if(system_upgrade_start(upServer) == false)
//	{
//		//    uart0_sendStr("+CIPUPDATE:0/r/n");
//		at_backError;
//		specialAtState = TRUE;
//		at_state = at_statIdle;
//	}
//	else
//	{
//		uart0_sendStr("+CIPUPDATE:4\r\n");
//	}
//	*/
//
//}
//
///**
//  * @brief  Udp server receive data callback function.
//  * @param  arg: contain the ip link information
//  * @retval None
//  */
//LOCAL void ICACHE_FLASH_ATTR
//at_upDate_recv(void *arg, char *pusrdata, unsigned short len)
//{
//  struct espconn *pespconn = (struct espconn *)arg;
//  char temp[32];
//  char *pTemp;
//  uint8_t user_bin[9] = {0};
////  uint8_t devkey[41] = {0};
//  uint8_t i;
//
////  os_printf("get upRom:\r\n");
//  uart0_sendStr("+CIPUPDATE:3\r\n");
//
////  os_printf("%s",pusrdata);
//  pTemp = (char *)os_strstr(pusrdata,"rom_version\": ");
//  if(pTemp == NULL)
//  {
//    return;
//  }
//  pTemp += sizeof("rom_version\": ");
//
////  user_esp_platform_load_param(&esp_param);
//
//  upServer = (struct upgrade_server_info *)os_zalloc(sizeof(struct upgrade_server_info));
//  os_memcpy(upServer->upgrade_version, pTemp, 5);
//  upServer->upgrade_version[5] = '\0';
//  os_sprintf(upServer->pre_version, "v%d.%d", XC_VERSION_main, XC_VERSION_sub);
//
//  upServer->pespconn = pespconn;
//
////  os_memcpy(devkey, esp_param.devkey, 40);
//  os_memcpy(upServer->ip, pespconn->proto.tcp->remote_ip, 4);
//
//  upServer->port = 80;
//
//  upServer->check_cb = at_upDate_rsp;
//  upServer->check_times = 60000;
//
//  if(upServer->url == NULL)
//  {
//    upServer->url = (uint8 *) os_zalloc(512);
//  }
//
//  if(system_upgrade_userbin_check() == UPGRADE_FW_BIN1)
//  {
//    os_memcpy(user_bin, "user2.bin", 10);
//  }
//  else if(system_upgrade_userbin_check() == UPGRADE_FW_BIN2)
//  {
//    os_memcpy(user_bin, "user1.bin", 10);
//  }
//
//  os_sprintf(upServer->url,
//        "GET /v1/device/rom/?action=download_rom&version=%s&filename=%s HTTP/1.1\r\nHost: "IPSTR":%d\r\n"pheadbuffer"",
//        upServer->upgrade_version, user_bin, IP2STR(upServer->ip),
//        upServer->port, KEY);
//
//  //  ESP_DBG(upServer->url);
//
////  espconn_disconnect(pespconn);
//}
//
///******************************************************************************
// * FunctionName : user_esp_platform_sent_cb
// * Description  : Data has been sent successfully and acknowledged by the remote host.
// * Parameters   : arg -- Additional argument to pass to the callback function
// * Returns      : none
//*******************************************************************************/
//LOCAL void ICACHE_FLASH_ATTR
//at_upDate_sent_cb(void *arg)
//{
//    struct espconn *pespconn = arg;
//
//    os_printf("at_upDate_sent_cb\r\n");
//}
//
///**
//  * @brief  Tcp client connect success callback function.
//  * @param  arg: contain the ip link information
//  * @retval None
//  */
//static void ICACHE_FLASH_ATTR
//at_upDate_connect_cb(void *arg)
//{
//  struct espconn *pespconn = (struct espconn *)arg;
//  uint8_t user_bin[9] = {0};
////  uint8_t devkey[41] = {0};
//  char *temp;
//
//  uart0_sendStr("+CIPUPDATE:2\r\n");
//
////  user_esp_platform_load_param(&esp_param);
////  os_memcpy(devkey, esp_param.devkey, 40);
//
//  espconn_regist_disconcb(pespconn, at_upDate_discon_cb);
//  espconn_regist_recvcb(pespconn, at_upDate_recv);////////
//  espconn_regist_sentcb(pespconn, at_upDate_sent_cb);
//
////  os_printf("at_upDate_connect_cb %p\r\n", arg);
//
//  temp = (uint8 *) os_zalloc(512);
//
//  os_sprintf(temp,"GET /v1/device/rom/?is_format_simple=true HTTP/1.0\r\nHost: "IPSTR":%d\r\n"pheadbuffer"",
//             IP2STR(pespconn->proto.tcp->remote_ip),
//             80, KEY);
//
//  espconn_sent(pespconn, temp, os_strlen(temp));
//  os_free(temp);
///////////////////////////
//}
//
///**
//  * @brief  Tcp client connect repeat callback function.
//  * @param  arg: contain the ip link information
//  * @retval None
//  */
//static void ICACHE_FLASH_ATTR
//at_upDate_recon_cb(void *arg, sint8 errType)
//{
//  struct espconn *pespconn = (struct espconn *)arg;
////  os_timer_t sta_timer;
////  static uint8_t repeaTime = 0;
////  char temp[32];
//
////  os_printf("at_upDate_recon_cb %p\r\n", arg);
//
////  repeaTime++;
////  if(repeaTime >= 3)
////  {
////    os_printf("repeat over %d\r\n", repeaTime);
////    repeaTime = 0;
//    at_backError;
//    if(pespconn->proto.tcp != NULL)
//    {
//      os_free(pespconn->proto.tcp);
//    }
//    os_free(pespconn);
//    os_printf("disconnect\r\n");
//
//    if(upServer != NULL)
//    {
//      os_free(upServer);
//      upServer = NULL;
//    }
//    at_backError;
////    os_sprintf(temp,at_backTeError,3);
////    uart0_sendStr(at_backTeError"3\r\n");
//
//    specialAtState = TRUE;
//    at_state = at_statIdle;
////    return;
////  }
////  os_printf("link repeat %d\r\n", repeaTime);
////  pespconn->proto.tcp->local_port = espconn_port();
////  espconn_connect(pespconn);
//}
//
///******************************************************************************
// * FunctionName : upServer_dns_found
// * Description  : dns found callback
// * Parameters   : name -- pointer to the name that was looked up.
// *                ipaddr -- pointer to an ip_addr_t containing the IP address of
// *                the hostname, or NULL if the name could not be found (or on any
// *                other error).
// *                callback_arg -- a user-specified callback argument passed to
// *                dns_gethostbyname
// * Returns      : none
//*******************************************************************************/
//LOCAL void ICACHE_FLASH_ATTR
//upServer_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
//{
//  struct espconn *pespconn = (struct espconn *) arg;
////  char temp[32];
//
//  if(ipaddr == NULL)
//  {
//    at_backError;
////    os_sprintf(temp,at_backTeError,2);
////    uart0_sendStr(at_backTeError"2\r\n");
//    specialAtState = TRUE;
//    at_state = at_statIdle;
////    device_status = DEVICE_CONNECT_SERVER_FAIL;
//    return;
//  }
//  uart0_sendStr("+CIPUPDATE:1\r\n");
//
////  os_printf("DNS found: %d.%d.%d.%d\n",
////            *((uint8 *) &ipaddr->addr),
////            *((uint8 *) &ipaddr->addr + 1),
////            *((uint8 *) &ipaddr->addr + 2),
////            *((uint8 *) &ipaddr->addr + 3));
//
//  if(host_ip.addr == 0 && ipaddr->addr != 0)
//  {
//    if(pespconn->type == ESPCONN_TCP)
//    {
//      os_memcpy(pespconn->proto.tcp->remote_ip, &ipaddr->addr, 4);
//      espconn_regist_connectcb(pespconn, at_upDate_connect_cb);
//      espconn_regist_reconcb(pespconn, at_upDate_recon_cb);
//      espconn_connect(pespconn);
//
////      at_upDate_connect_cb(pespconn);
//    }
//  }
//}
//
//void ICACHE_FLASH_ATTR
//at_exeCmdUpdate(uint8_t id)
//{
//  pespconn = (struct espconn *)os_zalloc(sizeof(struct espconn));
//  pespconn->type = ESPCONN_TCP;
//  pespconn->state = ESPCONN_NONE;
//  pespconn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
//  pespconn->proto.tcp->local_port = espconn_port();
//  pespconn->proto.tcp->remote_port = 80;
//
//  specialAtState = FALSE;
//  espconn_gethostbyname(pespconn, "iot.espressif.cn", &host_ip, upServer_dns_found);
//}
//
